package string;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1：
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * <p>
 * 示例 2：
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 * @author Jisheng Huang
 * @version 20250617
 */
public class LongestCommonPrefix_14 {
    /**
     * @param strs
     * @return
     */
    public static String longestCommonPrefix(String[] strs) {
        // Edge case: When strs is empty, return an empty string
        if (strs == null || strs.length == 0) {
            return "";
        }

        int length = strs[0].length();

        for (int i = 0; i < length; ++i) {
            char c = strs[0].charAt(i);

            for (int j = 1; j < strs.length; ++j) {
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }

        return strs[0];
    }

    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix(strs));

        strs = new String[]{"dog", "racecar", "car"};
        System.out.println(longestCommonPrefix(strs));
    }
}